import {computed, ref,unref} from 'vue'
import {defineStore} from 'pinia'
import {add as xe_add,multiply as xe_multiply} from "xe-utils"

const cartList=ref([])

export const useCartStore=defineStore('cart',()=>{
	
	//购物车商品数目
	const goodsNum=computed(()=>{
		return unref(cartList).reduce((pre,cur)=>{
			return xe_add(pre,Number(cur._countNum))
		},0)
	})
	//购物车商品总价
	const priceSum=computed(()=>{
		return unref(cartList).reduce((pre,cur)=>{
			return xe_add(pre,xe_multiply(Number(cur._countNum),Number(cur._skuInfo.price)))
		},0)
	})
	
	const pushGoods=(goods)=>{
		//判断商品是否一样(id)
		const {_id,_skuInfo:{_id:skuId},_countNum}=goods
		//寻找商品索引
		const index=unref(cartList).findIndex(item=>_id&&skuId&&(item._id==_id)&&(item._skuInfo._id==skuId))
		if(index>-1){
			//数目增加
			cartList.value[index]._countNum=Number(_countNum)+Number(cartList.value[index]._countNum)
		}
		else
		 cartList.value.unshift(goods)
	}
	return {
		cartList,
		pushGoods,
		goodsNum,
		priceSum
	}
})
